package com.example.fund.updatestategy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import com.example.fund.util.DBManager;

public class WY163AIndexStrategy extends AbstractUpdateStrategy
{

	private static final String indexURL = "http://quotes.money.163.com/service/chddata.html?code=codeV&start=from&end=to&fields=TCLOSE;VATURNOVER";
	
	public WY163AIndexStrategy(String number) 
	{
		super(number);
	}

	@Override
	public void updateIndex()
	{
		SQLiteDatabase db = DBManager.getDB();
		
		String maxDate = getFundMaxDate();
		
		String insertSql = "insert into FundNetValue(id,fundNumber,netValue,volume,date) values (null,?,?,?,?)";
		db.beginTransaction();
		SQLiteStatement stmt = db.compileStatement(insertSql);
		
		BufferedReader reader = null;
		HttpURLConnection con = null;
		String regex = "[0-9]{4}-[0-9]{2}-[0-9]{2}";
		BigDecimal tem = new BigDecimal("100000000");
		try {
			DateFormat df = new SimpleDateFormat("yyyyMMdd");
			String endDate = df.format(new Date());
			String adataURL = indexURL.replace("codeV", number).replace("from","19901219").replace("to", endDate);
			URL url = new URL(adataURL);
			con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");
			reader = new BufferedReader(new InputStreamReader(con.getInputStream(),"GBK"));
			String s = null;
			double lastVolume = 0;
			while ((s = reader.readLine()) != null) 
			{
				String[] shArray = s.split(",");
				if(shArray.length>=5)
				{
					if(Pattern.matches(regex, shArray[0]))
					{
						if(shArray[0].compareTo(maxDate)>0 && Double.valueOf(shArray[3])>0)
						{
						    stmt.bindString(1, number);  
						    stmt.bindDouble(2, Double.valueOf(shArray[3]));
						    double volume = lastVolume;
						    try {
						    	BigDecimal bigDecimal = new BigDecimal(shArray[4]).divide(tem, 4, RoundingMode.HALF_UP);
						    	volume = bigDecimal.doubleValue();
							} catch (Exception e) {
							}
						    lastVolume = volume;
						    stmt.bindDouble(3, volume);
						    stmt.bindString(4, shArray[0]);  
						    stmt.execute();  
						    stmt.clearBindings(); 
						}
					}
				}
			}
			
			db.setTransactionSuccessful();  
		} catch(Exception e) 
		{
			e.printStackTrace();
		} finally
		{
			db.endTransaction();
			try 
			{
				if(reader!=null)
				{
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(con!=null)
			{
				con.disconnect();
			}
		}
	}

}
